/* global alert wx OSS File atob AliyunUpload*/
var _uploadCount = Number(uploadCount);
String.prototype.padLeft = Number.prototype.padLeft = function (total, pad) {
        return (Array(total).join(pad || 0) + this).slice(-total);
    };

function get_object_name(uuid, suffix) {
    //取得系统日期
    var now = new Date();
    var year = now.getFullYear().padLeft(4);
    var month = (now.getMonth() + 1).padLeft(2);
    var day = now.getDate().padLeft(2);
    var path = 'file/' + year + '/' + month + day + '/';
    return path + uuid + '.' + suffix;
}

function get_upload_param(suffix) {
    var uuid = guid();
    return {
        'key': get_object_name(uuid, suffix),
        'uuid': uuid,
        'filename': uuid + '.' + suffix
    };
}
var ua = navigator.userAgent.toLowerCase();
if(ua.indexOf('windows') != -1){
    //上传图片
    $('#imageUpload').on('change', function (e) {
        var length = e.target.files.length;
        var files = e.target.files;  //FileList Objects
        var i = 0;    
        function upload() {
            var filename = files[i].name;
            var filenameAry = filename.split('.');
            var fileInfo = get_upload_param(filenameAry[filenameAry.length - 1]);
            var client = new OSS({
                region: 'oss-cn-hangzhou',
                accessKeyId: 'LTAITldlbkDhCEVv',
                accessKeySecret: 'x7hE3GZFzmJkvkjdbWu9lkp78hoq6A',
                bucket: 'gjbhz',
                secure: true
            });
            client.put(fileInfo.key, files[i]).then(function (result) {
                i++;
                $.showLoading('上传' + i + '/' + length + '图片中...');
                //alert('上传成功');
                //alert(JSON.stringify(result.res));
                var url = result.res.requestUrls[0];
                var imgObj = $('<div class="img" style="background: url(' + url + '?x-oss-process=image/resize,w_400) no-repeat 0 center;background-size: 100% auto;"></div>').attr({
                    url: url
                }).click(function () {
                    var url = $(this).attr('url');
                    var imgArray = [];
                    for (var i = 0; i < $('#ossfile .img').length; i++) {
                        imgArray.push($('#ossfile .img').eq(i).attr('url'));
                    }
                    wx.previewImage({
                        current: url, // 当前显示图片的http链接
                        urls: imgArray // 需要预览的图片http链接列表
                    });
                });
                var delObj = $('<svg t="1552392959791" class="icon" style="width:0.8rem;height:0.8rem;position:absolute;top:0.1rem;right:0.1rem;cursor:pointer;" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5486" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><defs><style type="text/css"></style></defs><path d="M512 32C246.4 32 32 246.4 32 512s214.4 480 480 480 480-214.4 480-480S777.6 32 512 32" fill="#FF2828" p-id="5487"></path><path d="M713.6 713.6c-12.8 12.8-35.2 12.8-48 0l-153.6-153.6-153.6 153.6c-12.8 12.8-35.2 12.8-48 0s-12.8-35.2 0-48l153.6-153.6-153.6-153.6c-12.8-12.8-12.8-35.2 0-48s35.2-12.8 48 0l153.6 153.6 153.6-153.6c12.8-12.8 35.2-12.8 48 0s12.8 35.2 0 48l-153.6 153.6 153.6 153.6c16 12.8 16 35.2 0 48z" fill="#FFFFFF" p-id="5488"></path></svg>')
                .click(function () {
                    $(this).parent().remove();
                    registerImgCount(-1);
                }).appendTo(imgObj);
                imgObj.appendTo('#ossfile');
                if (i < length) {
                    upload();
                } else {
                    $.showLoading('谢谢使用上传完毕!');
                    setTimeout(function() {
                        $.hideLoading();
                    }, 200);    
                    if (_uploadCount != 1){
                        calculationImgJson();
                        new Sortable(document.getElementById('ossfile'), {
                            animation: 150,
                            ghostClass: 'blue-background-class',
                            onEnd: function (evt) {},
                            // Changed sorting within list
                            onUpdate: function (evt) {
                                var itemEl = evt.item; // dragged HTMLElement
                                calculationImgJson();
                            }
                        });
                    } else {
                        $('#image').val(url);
                    }
                }
            });
        }
        upload();
    });
} else {
    $('#imageUpload').hide();
}


//选择图片
var access_token = '';
$("#selectfiles").click(function () {
    $.post('/antique/api/wxApi/getticket', {
        url: window.location.href
    }, function (result) {
        access_token = result.data.access_token;
        wx.config({
            debug: false,
            appId: result.data.appid,
            timestamp: result.data.timestamp,
            nonceStr: result.data.noncestr,
            signature: result.data.signature,
            jsApiList: [
                // 所有要调用的 API 都要加到这个列表中
                'chooseImage',
                'previewImage',
                'uploadImage',
                'downloadImage',
                'getLocalImgData'
            ]
        });
        wx.ready(function () {
            wx.checkJsApi({
                jsApiList: [
                    'chooseImage',
                    'previewImage',
                    'uploadImage',
                    'downloadImage',
                    'getLocalImgData'
                ],
                success: function (res) {
                    //alert(JSON.stringify(res));
                    //alert(JSON.stringify(res.checkResult.getLocation));
                    if (res.checkResult.getLocation == false) {
                        alert('你的微信版本太低，不支持微信JS接口，请升级到最新的微信版本！');
                        return;
                    } else {
                        wxChooseImage();
                    }
                }
            });
        });
        wx.error(function (res) {
            // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
            alert("验证失败，请重试！");
            wx.closeWindow();
        });
    });
});
var images = {
    localId: [],
    serverId: [],
    count:$('#ossfile .img').length>0?$('#ossfile .img').length:0
};
//监听上传图片寄存器
function registerImgCount(num){
    images.count = images.count + num;
    if(images.count >= _uploadCount){
        $('#selectfiles').parent().hide();
    } else {
        $('#selectfiles').parent().show();
    }
    uploadCount = uploadCount - images.count;
}

//重新计算图片的内容
function calculationImgJson(){
    var showImages = '';
    for (var i = 0; i < $('#ossfile .img').length; i++) {
        if (i == $('#ossfile .img').length - 1) {
            showImages += $('#ossfile .img').eq(i).attr('url');
        } else {
            showImages += $('#ossfile .img').eq(i).attr('url') + ',';
        }
    }
    $('#showImages').val(showImages);
}

registerImgCount(0);
//拍照或从手机相册中选图接口
/* global uploadCount Sortable*/
function wxChooseImage() {
    wx.chooseImage({
        count: uploadCount, // 默认9
        sizeType: ['original'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) {
            images.localId = res.localIds;
            if (images.localId.length == 0) {
                alert('请先使用 chooseImage 接口选择图片');
                return;
            }
            var i = 0,length = images.localId.length;
            //alert('_uploadCount=>' + _uploadCount);
            //alert('images.count=>' + images.count);
            //alert('#ossfile .img length=>' + $('#ossfile .img').length);
            //alert('总和=>' + (images.count) + length);
            if (parseInt(images.count) + length > _uploadCount){
                $.toast('你选择的图片数量已经超过了上传的最大数量!');
                return false;
            }
            function upload() {
                //图片上传
                wx.uploadImage({
                    localId: images.localId[i],
                    isShowProgressTips: 1,
                    success: function (res) {
                        i++;
                        $.showLoading('上传' + i + '/' + length + '图片中...');
                        var serverId = res.serverId; // 返回图片的服务器端ID
                        //var url = 'http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=' + access_token + '&media_id=' + serverId;                        
                        //通过ajax来将base64数据转换成图片保存在本地
                        $.get('/uploadToOss',{
                            mediaId:serverId,
                            accessToken:access_token
                        },function(data){
                            var url = data.url;
                            var imgObj = $('<div class="img" style="background: url(' + url + '?x-oss-process=image/resize,w_400) no-repeat 0 center;background-size: 100% auto;"></div>').attr({
                                url:url
                            }).click(function(){
                                var url = $(this).attr('url');
                                var imgArray = [];                    
                                for (var i = 0 ;i < $('#ossfile .img').length;i++){
                                    imgArray.push($('#ossfile .img').eq(i).attr('url'));
                                }
                                wx.previewImage({
                                    current: url, // 当前显示图片的http链接
                                    urls: imgArray // 需要预览的图片http链接列表
                                });
                            });
                            var delObj = $('<svg t="1552392959791" class="icon" style="width:0.8rem;height:0.8rem;position:absolute;top:0.1rem;right:0.1rem;cursor:pointer;" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5486" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><defs><style type="text/css"></style></defs><path d="M512 32C246.4 32 32 246.4 32 512s214.4 480 480 480 480-214.4 480-480S777.6 32 512 32" fill="#FF2828" p-id="5487"></path><path d="M713.6 713.6c-12.8 12.8-35.2 12.8-48 0l-153.6-153.6-153.6 153.6c-12.8 12.8-35.2 12.8-48 0s-12.8-35.2 0-48l153.6-153.6-153.6-153.6c-12.8-12.8-12.8-35.2 0-48s35.2-12.8 48 0l153.6 153.6 153.6-153.6c12.8-12.8 35.2-12.8 48 0s12.8 35.2 0 48l-153.6 153.6 153.6 153.6c16 12.8 16 35.2 0 48z" fill="#FFFFFF" p-id="5488"></path></svg>')
                            .click(function(){
                                $(this).parent().remove();
                                registerImgCount(-1);
                            }).appendTo(imgObj);
                            imgObj.appendTo('#ossfile');
                            registerImgCount(1);
                            if (i < length) {
                                upload();
                            } else {
                                $.showLoading('谢谢使用上传完毕!');
                                setTimeout(function() {
                                    $.hideLoading();
                                }, 200); 
                                if (_uploadCount != 1){
                                    calculationImgJson();
                                    new Sortable(document.getElementById('ossfile'), {
                                        animation: 150,
                                        ghostClass: 'blue-background-class',
                                        onEnd:function(evt){
                                        },
                                        // Changed sorting within list
                                        onUpdate: function (evt) {
                                            var itemEl = evt.item; // dragged HTMLElement
                                            // + indexes from onEnd
                                            calculationImgJson();
                                        },
                                    });
                                } else {
                                    $('#image').val(url);
                                }
                            }
                        });
                    },
                    fail: function (res) {
                        alert(JSON.stringify(res));
                    }
                });
            }
            upload();
        },
        fail: function (res) {
            alert(JSON.stringify(res));
        }
    });
}

/**
 * base64 to file
 * @param dataurl   base64 content
 * @param filename  set up a meaningful suffix, or you can set mime type in options
 * @returns {File|*}
 */
function dataURLtoFile(dataurl, filename) {
    var arr = dataurl.split(',');
    var mime = arr[0].match(/:(.*?);/)[1];
    var bstr = atob(arr[1]);
    var n = bstr.length;
    var u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, {
        type: mime
    }); // if env support File, also can use this: return ;
}

//用于生成uuid
function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}

function guid() {
    return (S4() + S4() + S4() + S4() + S4() + S4() + S4() + S4());
}



/** 
 * 创建一个视频上传对象
 * 使用 UploadAuth 上传方式
 */
var videoCount = $('#ossvideo .img').length>0?$('#ossvideo .img').length:0;
function registerVideoCount(num){
    videoCount = videoCount + num;
    if(videoCount >= 1){
        $('#selectvideos').parent().hide();
    } else {
        $('#selectvideos').parent().show();
    }
}
registerVideoCount(0);
function createUploader() {    
    var uploader = new AliyunUpload.Vod({
        timeout: 60000,
        partSize: 1024 * 1024,
        parallel: 5,
        retryCount: 3,
        retryDuration: 2,
        region: 'cn-shanghai',
        userId: '1720442442383302',
        // 添加文件成功
        addFileSuccess: function (uploadInfo) {
            console.log('addFileSuccess');
            uploader.startUpload();
            console.log("addFileSuccess: " + uploadInfo.file.name);
        },
        // 开始上传
        onUploadstarted: function (uploadInfo) {
            //文件大小不得超过30M
            console.log(uploadInfo);
            if(uploadInfo.file.size > 1024 * 1024 * 36){
                $.toast('上传的视频大小不得超过36mb,尽量控制时长不要超过10秒!');
                return false;
            }
            // 如果是 UploadAuth 上传方式, 需要调用 uploader.setUploadAuthAndAddress 方法
            // 如果是 UploadAuth 上传方式, 需要根据 uploadInfo.videoId是否有值，调用点播的不同接口获取uploadauth和uploadAddress
            // 如果 uploadInfo.videoId 有值，调用刷新视频上传凭证接口，否则调用创建视频上传凭证接口
            // 注意: 这里是测试 demo 所以直接调用了获取 UploadAuth 的测试接口, 用户在使用时需要判断 uploadInfo.videoId 存在与否从而调用 openApi
            // 如果 uploadInfo.videoId 存在, 调用 刷新视频上传凭证接口(https://help.aliyun.com/document_detail/55408.html)
            // 如果 uploadInfo.videoId 不存在,调用 获取视频上传地址和凭证接口(https://help.aliyun.com/document_detail/55407.html)
            $.showLoading('上传视频中...');
            if (!uploadInfo.videoId) {
                var createUrl = '/getUploadOssVoucher';
                $.get(createUrl, {
                    filename:uploadInfo.file.name
                },function (result) {
                    var uploadAuth = result.data.UploadAuth;
                    var uploadAddress = result.data.UploadAddress;
                    var videoId = result.data.VideoId;
                    uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId);
                }, 'json');
                $('#status').text('文件开始上传...');
                console.log("onUploadStarted:" + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object);
            } else {
                // 如果videoId有值，根据videoId刷新上传凭证
                // https://help.aliyun.com/document_detail/55408.html?spm=a2c4g.11186623.6.630.BoYYcY
                var refreshUrl = '/refreshUploadOssVoucher?videoId=' + uploadInfo.videoId;
                $.get(refreshUrl, function (result) {
                    var uploadAuth = result.data.UploadAuth;
                    var uploadAddress = result.data.UploadAddress;
                    var videoId = result.data.VideoId;
                    uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId);
                }, 'json');
            }
        },
        // 文件上传成功
        onUploadSucceed: function (uploadInfo) {
            console.log(uploadInfo);
            //alert(JSON.stringify(uploadInfo));
            console.log("onUploadSucceed: " + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object);
            $('#status').text('文件上传成功!');
            //截取视频第一帧为图片
            $.get('/submitSnapshotJob',{
                videoId:uploadInfo.videoId
            },function(result){
                $.showLoading('上传完毕截图中..');
                var requestFinish = false;
                //获得视频相关信息
                function requestSnapshots(){
                    $.get('/listSnapshots',{
                        videoId:uploadInfo.videoId,
                    },function(result){
                        if (result.code == 100){
                            requestFinish = true;
                            var url = result.data.MediaSnapshot.Snapshots.Snapshot[0].Url;
                            // eslint-disable-next-line no-inner-declarations
                            function getPlayInfo(){
                                $.get('/getPlayInfo?videoId=' + uploadInfo.videoId,function(result){
                                    $.showLoading('截图完毕解码中..');
                                    if (result.code == 100){
                                        registerVideoCount(1);
                                        //取得mp4格式的播放对象
                                        var playVideo = '';
                                        for (var i = 0;i < result.data.length; i++){
                                            if (result.data[i].Format == 'mp4'){
                                                playVideo = result.data[i].PlayURL;
                                                break;
                                            }
                                        }
                                        if (playVideo == ''){
                                            window.setTimeout(function(){
                                                getPlayInfo();
                                            },300);
                                            return;
                                        }

                                        //把视频信息保存入input中
                                        $('#showVideos').val(uploadInfo.videoId);
                                        var imgObj = $('<div class="img" style="background: url(' + url + ') no-repeat 0 center;background-size: 100% auto;"></div>').attr({
                                            videoId: uploadInfo.videoId
                                        }).click(function () {
                                            var playerContainer = $('<div></div>').attr('id','playerContainer').css({
                                                position:'fixed',
                                                width:'100%',
                                                height:'100%',
                                                display:'none',
                                                top: '0',
                                                zIndex:'9999'
                                            }).appendTo(window.document.body);
                                            /* global Aliplayer */
                                            var videoId = $(this).attr('videoId');
                                            $.get('/getPlayInfo?videoId=' + videoId,function(result){
                                                var playVideo = '';
                                                for (var i = 0;i < result.data.length; i++){
                                                    if (result.data[i].Format == 'mp4'){
                                                        playVideo = result.data[i].PlayURL;
                                                        break;
                                                    }
                                                }
                                                //$.get('/log',{info:'playVideo => ' + playVideo});
                                                //$.get('/log',{info:'playerContainer.length => ' + $('#playerContainer').length});
                                                
                                                var player = new Aliplayer({
                                                    "id": "playerContainer",
                                                    "source": playVideo,
                                                    "width": "100%",
                                                    "height": "500px",
                                                    "autoplay": true,
                                                    "isLive": false,
                                                    "rePlay": true,
                                                    "playsinline": true,
                                                    "preload": true,
                                                    "controlBarVisibility": "hover",
                                                    "useH5Prism": true
                                                }, function (player) {
                                                    player._switchLevel = 0;
                                                    console.log("播放器创建了。");
                                                });
                                                var closeVideo = $('<svg id="closeVideo" t="1552392959791" class="icon" style="width:1.2rem;height:1.2rem;position:absolute;top:0.1rem;right:0.1rem;cursor:pointer;" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5486" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><defs><style type="text/css"></style></defs><path d="M512 32C246.4 32 32 246.4 32 512s214.4 480 480 480 480-214.4 480-480S777.6 32 512 32" fill="#FF2828" p-id="5487"></path><path d="M713.6 713.6c-12.8 12.8-35.2 12.8-48 0l-153.6-153.6-153.6 153.6c-12.8 12.8-35.2 12.8-48 0s-12.8-35.2 0-48l153.6-153.6-153.6-153.6c-12.8-12.8-12.8-35.2 0-48s35.2-12.8 48 0l153.6 153.6 153.6-153.6c12.8-12.8 35.2-12.8 48 0s12.8 35.2 0 48l-153.6 153.6 153.6 153.6c16 12.8 16 35.2 0 48z" fill="#FFFFFF" p-id="5488"></path></svg>');
                                                playerContainer.show().append(closeVideo);
                                                closeVideo.click(function(){
                                                    var _parent = $(this).parent();
                                                    player.stop();
                                                    _parent.remove();
                                                });
                                            });
                                        });
                                        var delObj = $('<svg t="1552392959791" class="icon" style="width:0.8rem;height:0.8rem;position:absolute;top:0.1rem;right:0.1rem;cursor:pointer;" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5486" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><defs><style type="text/css"></style></defs><path d="M512 32C246.4 32 32 246.4 32 512s214.4 480 480 480 480-214.4 480-480S777.6 32 512 32" fill="#FF2828" p-id="5487"></path><path d="M713.6 713.6c-12.8 12.8-35.2 12.8-48 0l-153.6-153.6-153.6 153.6c-12.8 12.8-35.2 12.8-48 0s-12.8-35.2 0-48l153.6-153.6-153.6-153.6c-12.8-12.8-12.8-35.2 0-48s35.2-12.8 48 0l153.6 153.6 153.6-153.6c12.8-12.8 35.2-12.8 48 0s12.8 35.2 0 48l-153.6 153.6 153.6 153.6c16 12.8 16 35.2 0 48z" fill="#FFFFFF" p-id="5488"></path></svg>')
                                        .click(function () {
                                            $(this).parent().remove();
                                            $('#showVideos').val('');
                                            registerVideoCount(-1);                                            
                                        }).appendTo(imgObj);
                                        $.showLoading('谢谢使用操作完成!');
                                        setTimeout(function() {
                                            $.hideLoading();
                                        }, 200);
                                        imgObj.appendTo('#ossvideo');
                                    } else {
                                        window.setTimeout(function(){
                                            getPlayInfo();
                                        },300);
                                    }
                                });
                            }
                            getPlayInfo();
                        }
                        if (!requestFinish){
                            window.setTimeout(function(){
                                requestSnapshots();
                            },300);
                        }
                    });
                }
                requestSnapshots();
            });
        },
        // 文件上传失败
        onUploadFailed: function (uploadInfo, code, message) {
            console.log("onUploadFailed: file:" + uploadInfo.file.name + ",code:" + code + ", message:" + message);
            $('#status').text('文件上传失败!');
        },
        // 取消文件上传
        onUploadCanceled: function (uploadInfo, code, message) {
            console.log("Canceled file: " + uploadInfo.file.name + ", code: " + code + ", message:" + message);
            $('#status').text('文件上传已暂停!');
        },
        // 文件上传进度，单位：字节, 可以在这个函数中拿到上传进度并显示在页面上
        onUploadProgress: function (uploadInfo, totalSize, progress) {
            console.log("onUploadProgress:file:" + uploadInfo.file.name + ", fileSize:" + totalSize + ", percent:" + Math.ceil(progress * 100) + "%");
            var progressPercent = Math.ceil(progress * 100);
            $('#auth-progress').text(progressPercent);
            $('#status').text('文件上传中...');
        },
        // 上传凭证超时
        onUploadTokenExpired: function (uploadInfo) {
            // 上传大文件超时, 如果是上传方式一即根据 UploadAuth 上传时
            // 需要根据 uploadInfo.videoId 调用刷新视频上传凭证接口(https://help.aliyun.com/document_detail/55408.html)重新获取 UploadAuth
            // 然后调用 resumeUploadWithAuth 方法, 这里是测试接口, 所以我直接获取了 UploadAuth
            $('#status').text('文件上传超时!');

            var refreshUrl = '/refreshUploadOssVoucher?videoId=' + uploadInfo.videoId;
            $.get(refreshUrl, function (result) {
                var uploadAuth = result.data.UploadAuth;
                uploader.resumeUploadWithAuth(uploadAuth);
                console.log('upload expired and resume upload with uploadauth ' + uploadAuth);
            }, 'json');
        },
        // 全部文件上传结束
        onUploadEnd: function (uploadInfo) {
            $('#status').text('文件上传完毕!');
            console.log("onUploadEnd: uploaded all the files");
        }
    });
    return uploader;
}

var uploader = null;
//上传视频
$('#fileUpload').on('change', function (e) {
    var file = e.target.files[0];
    if (!file) {
        alert("请先选择需要上传的文件!");
        return;
    }
    var Title = file.name;
    var userData = '{"Vod":{}}';
    if (uploader) {
        uploader.stopUpload();
        $('#auth-progress').text('0');
        $('#status').text("");
    }
    uploader = createUploader();
    // 首先调用 uploader.addFile(event.target.files[i], null, null, null, userData)
    uploader.addFile(file, null, null, null, userData);
});